import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "./form.vue";

import {
  productFlowlogListApi,
  productFlowlogShowApi
} from "@/api/purchaseOrderApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 10,
    productId: null,
    purchaseOrderId: null,
    storeId: null,
    type: null,
    deliveryOrderId: null,
    storeCheckId: null,
    rangeCreatedTime: null,
    sortType: null,
    sortOrder: null,
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const typeOption = ref([
    {id: 1, name: '上架入库'},
    {id: 2, name: '下架出库'},
    {id: 3, name: '盘盈入库'},
    {id: 4, name: '盘亏出库'},
    {id: 5, name: '撤销废止'},
  ])

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "productFlowlogId",
      width: 70,
      sortable: true,
    },
    {
      label: "产品名称",
      prop: "product.productName",
      minWidth: 150,
      formatter: (row) => {
        return row.product?.productName || '--';
      }
    },
    {
      label: "产品编号",
      prop: "product.productNo",
      minWidth: 150,
      formatter: (row) => {
        return row.product?.productNo || '--';
      }
    },
    {
      label: "单据类型",
      prop: "type",
      slot: "type",
    },
    {
      label: "所属订单",
      prop: "purchaseOrder.orderDate",
      minWidth: 100,
      formatter: (row) => {
        let str = '--'
        if(row.type === 1 || row.type === 5) {
          str = '入库单'
        } else if(row.type === 2) {
          str = '出库单'
        } else if(row.type === 3 || row.type === 4) {
          str = '盘货单'
        }
        return str;
      }
    },

    {
      label: "订单编号",
      prop: "purchaseOrder.orderNo",
      minWidth: 150,
      formatter: (row) => {
        let str = '--'
        if(row.type === 1 || row.type === 5) {
          str = row.purchaseOrder.orderNo
        } else if(row.type === 2) {
          str = row.deliveryOrder.orderNo
        } else if(row.type === 3 || row.type === 4) {
          str = row.storeCheck.checkNo
        }
        return str;
      }
    },
    {
      label: "变化数量",
      prop: "changeNum",
      slot: "changeNum",
      minWidth: 120,
    },
    {
      label: "仓库",
      prop: "store.name",
      minWidth: 100,
    },

    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 160,
      sortable: true,
    },

    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 90
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch(index?: number) {
    if(index === 1) {
      form.page = index
    }
    loading.value = true;
    let params = {
      page: form.page,
      perPage: form.perPage,
      storeId: form.storeId,
      productId: form.productId,
      type: form.type,
      purchaseOrderId: form.purchaseOrderId,
      deliveryOrderId: form.deliveryOrderId,
      storeCheckId: form.storeCheckId,
      createdStartAt: form.rangeCreatedTime ? form.rangeCreatedTime[0] + ' 00:00:00' : null,
      createdEndAt: form.rangeCreatedTime ? form.rangeCreatedTime[1] + ' 23:59:59' : null,
      sortType: form.sortType,
      sortOrder: form.sortOrder,
    }
    const res: any = await productFlowlogListApi(cleanEmptyData(params));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;
    pagination.currentPage = res?.result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.productId = null;
    form.purchaseOrderId = null;
    form.storeId = null;
    form.type = null;
    form.deliveryOrderId = null;
    form.storeCheckId = null;
    form.rangeCreatedTime = null;
    form.sortType = null;
    form.sortOrder = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建流水", row: any) {
    const res: any = await productFlowlogShowApi({
      productFlowlogId: row.productFlowlogId
    })

    let formInline = {
      title: title,
      productInfo: res?.result,
      typeOption: typeOption.value
    };
    console.log(formInline.productInfo)
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: true,
      contentRenderer: () => h(editForm, { ref: formRef }),

    });
  }
  onMounted(async () => {
    onSearch();

  });
  function sortChange (column, prop, order) {
    form.sortOrder = "";
    if (column.order == "descending") {
      form.sortOrder = "desc";
      if (column.prop === "productFlowlogId") {
        form.sortType = "id";
      } else if(column.prop === 'totalNum') {
        form.sortType = "total_num";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'status') {
        form.sortType = "status";
      } else {
        form.sortType = column.prop;
      }
    } else if (column.order == "ascending") {
      form.sortOrder = "asc";
      if (column.prop === "productFlowlogId") {
        form.sortType = "id";
      } else if(column.prop === 'totalNum') {
        form.sortType = "total_num";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'status') {
        form.sortType = "status";
      } else {
        form.sortType = column.prop;
      }
    } else {
      form.sortOrder = "";
      form.sortType = "";
    }
    onSearch()
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    typeOption,
    sortChange
  };
}
